package com.skytech.component.crawler.scratch;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CrawlerUrlService {
    @Autowired
    private CrawlerUrlDAO crawlerUrlDAO;

    @Autowired
    private TargetRulesDAO targetRulesDAO;
    @Value("${pageNum}")
    private  int pageSize;


    //public Map<String,List<CrawlerUrl>> getCawlerUrl() {
    public Map<String,Integer> getCawlerUrl() {
        List<String> crawlerUrlList=new ArrayList<>();
         targetRulesDAO.findAll().stream().forEach(item->crawlerUrlList.add(item.getId()));
        List<String> stringList =crawlerUrlList.stream().distinct().collect(Collectors.toList());

        Map<String,Integer> crawlerUrlMap=new HashMap<>();
       /* for (String c:stringList) {
            crawlerUrlMap.put(c, crawlerUrlDAO.findGroupByRuleId(c));
        }*/
        for (String c:stringList) {
            if(null==crawlerUrlDAO.findGroupByRuleId(c)){
                crawlerUrlMap.put(c, 0);
            }else{
                crawlerUrlMap.put(c, crawlerUrlDAO.findGroupByRuleId(c));
            }

        }
        return crawlerUrlMap;

    }


    public Page<CrawlerUrl> findByRuleId(String ruleId,int pageNumber) {
        Pageable pageable = PageRequest.of(pageNumber,pageSize);
        return crawlerUrlDAO.findByRuleId(ruleId,pageable);
    }
}
